# -*- coding: utf-8 -*-
import numpy as np
from sklearn.utils import check_random_state
from sklearn.model_selection import train_test_split
import re


def load_txt_regex(path, delimiter=r'\s+'):
    pattern = re.compile(delimiter)
    data = []
    with open(path, 'r') as file:
        for line in file.readlines():
            tmp = pattern.split(line.strip())
            data.append(list(map(float, tmp)))
    return np.array(data)


def bootstrap_sampling(X, y=None, size=None, random_state=None):
    """
    Params
    -------
        X: 不含标签的数据，形状为2-D
        y: 数据标签，默认值为None时，不返回y的采样。形状为1-D
        size: 取样大小，默认为与X同样大小
        random_state: 随机的seed
    Return
    -------
        数据的采样
    """
    random_state = check_random_state(random_state)
    if size is None:
        size = len(X)
    samples = []
    labels = []
    for i in range(size):
        inx = int(random_state.rand() * len(X))
        samples.append(X[inx])
        if y is not None:
            labels.append(y[inx])
    if y is not None:
        return np.array(samples), np.array(labels)
    else:
        return np.array(samples)


# 读取数据集划分训练,测试,有标签,无标签数据
def gen_data(path, unlabeled_rate, delimiter=',', random_state=919):
    data = np.loadtxt(path, delimiter=delimiter)
    data_pos = data[data[:, 0] == 1.0]
    data_neg = data[data[:, 0] == -1.0]
    train_pos_data, test_pos_data, train_pos_label, test_pos_label = \
        train_test_split(data_pos[:, 1:], data_pos[:, 0], random_state=random_state)
    train_neg_data, test_neg_data, train_neg_label, test_neg_label = \
        train_test_split(data_neg[:, 1:], data_neg[:, 0], random_state=random_state)
    train_data = np.concatenate((train_pos_data, train_neg_data), axis=0)
    train_label = np.concatenate((train_pos_label, train_neg_label), axis=0)
    test_data = np.concatenate((test_pos_data, test_neg_data), axis=0)
    test_label = np.concatenate((test_pos_label, test_neg_label), axis=0)
    labeled_data, unlabeled_data, labeled_label, unlabeled_label = \
        train_test_split(train_data, train_label, test_size=unlabeled_rate, random_state=random_state)
    return train_data, train_label, test_data, test_label, labeled_data, labeled_label, unlabeled_data, unlabeled_label


if __name__ == '__main__':
    pass
